package tree;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description: 538. 把二叉搜索树转换为累加树
 * User: Li_yizYa
 * Date: 2025/6/11
 * Time: 21:50
 */
public class Solution37 {
    /**
     * 非递归
     * @param root
     * @return
     */
    public TreeNode convertBST1(TreeNode root) {
        if (root == null || root.left == null && root.right == null) {
            return root;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        int sum = 0;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.right;
            } else {
                TreeNode node = stack.pop();
                sum += node.val;
                node.val = sum;
                cur = node.left;
            }
        }
        return root;
    }
    /**
     * 递归写法
     */
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if (root == null || root.left == null && root.right == null) {
            return root;
        }
        traversal(root);
        return root;
    }
    private void traversal(TreeNode root) {
        if (root == null) {
            return;
        }
        traversal(root.right);
        sum += root.val;
        root.val = sum;
        traversal(root.left);
    }
}
